package com.xgx.distqcp.Common;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;

public class MongoDBHelper {
    public static void Test(){

        MongoClient mongoClient = Connect("192.168.247.131", 27017);
        MongoDatabase database = mongoClient.getDatabase("lessons");
        MongoCollection<Document> mc = database.getCollection("blog");
        //每次执行前清空集合以方便重复运行
        mc.drop();
        Document doc1 = new Document("title", "good day").append("owner", "tom").append("words", 300)
                .append("comments", Arrays.asList(new Document("author", "joe").append("score", 3).append("comment", "good"), new Document("author", "white").append("score", 1).append("comment", "oh no")));
        Document doc2 = new Document("title", "good").append("owner", "john").append("words", 400)
                .append("comments", Arrays.asList(new Document("author", "william").append("score", 4).append("comment", "good"), new Document("author", "white").append("score", 6).append("comment", "very good")));
        Document doc3 = new Document("title", "good night").append("owner", "mike").append("words", 200)
                .append("tag", Arrays.asList(1, 2, 3, 4));
        Document doc4 = new Document("title", "happiness").append("owner", "tom").append("words", 1480)
                .append("tag", Arrays.asList(2, 3, 4));
        Document doc5 = new Document("title", "a good thing").append("owner", "tom").append("words", 180)
                .append("tag", Arrays.asList(1, 2, 3, 4, 5));
        mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));

        //测试: 查询全部
        FindIterable<Document> iterable = mc.find();
        printResult("find all", iterable);


        mongoClient.close();
    }
    public static MongoClient Connect(String Ip,int Port){

        return new MongoClient(Ip, Port);
    }
    public static MongoClient Connect(){

        return Connect("192.168.247.131", 27017);
    }
    private static void printResult(String find_all, FindIterable<Document> iterable) {

        iterable.forEach(new Block<Document>() {
            public void apply(final Document document) {
                System.out.println(document);
            }
        });
        System.out.println("------------------------------------------------------");
        System.out.println();
    }
}
